package com.zzyl.service.impl;

import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private WechatService wechatService;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 1.调用微信接口，获取openid
        String openid = wechatService.getOpenid(userLoginRequestDto.getCode());

        // 2.根据openid查询数据库，判断用户是否存在
        Member member = memberMapper.selectByOpenid(openid);

        // 3.如果用户不存在，则进行注册
        if (member == null) {
            member = new Member();
            member.setOpenId(openid);
        }

        // 4.获取用户手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());

        // 5.新增或更新用户信息
        saveOrUpdate(member, phone);

        // 6.生成登录凭据，即JWT令牌，并返回
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.JWT_USERID, member.getId());
        claims.put(Constants.JWT_USERNAME, member.getName());
        String jwt = JwtUtil.createJWT(jwtProperties.getBase64EncodedSecretKey(), jwtProperties.getTtl(), claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(jwt);
        loginVo.setNickName(member.getName());
        return loginVo;
    }

    private void saveOrUpdate(Member member, String phone) {
        if (member.getId() == null) {
            // 新增用户
            member.setPhone(phone);
            member.setName(generateNickname());
            memberMapper.insert(member);
        } else {
            if (!StrUtil.equals(member.getPhone(), phone)) {
                // 更新用户信息
                member.setPhone(phone);
                memberMapper.updateSelective(member);
            } else {
                memberMapper.update(member);
            }
        }
    }

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int NICKNAME_LENGTH = 8; // 可以根据需要更改昵称长度

    public String generateNickname() {
        Random random = new Random();
        StringBuilder nickname = new StringBuilder(NICKNAME_LENGTH);
        for (int i = 0; i < NICKNAME_LENGTH; i++) {
            // 获取0到字符串长度的随机索引
            int index = (int) (random.nextFloat() * CHARACTERS.length());
            // 使用charAt方法获取随机字符并添加到昵称中
            nickname.append(CHARACTERS.charAt(index));
        }
        return nickname.toString();
    }


}
